package cn.hiapi.core.utils;

import java.util.concurrent.*;

/**
 * @author : AdinZ  1454269@qq.com
 * @Description:
 * @date Date : 2018年12月18日 15:33
 **/

public class TaskExecutor {
    private static TaskExecutor taskExecutor = null;
    private final BlockingQueue<Runnable> queue;
    private ThreadPoolExecutor executor;
    private static final int corePoolSize = 100;
    private static final int maximumPoolSize = 1024 * 1024;
    private static final long keepAliveTime = 2;

    public void shutdown() {
        if (executor != null) {
            executor.shutdown();
            executor = null;
        }
    }

    public static TaskExecutor getInstance() {
        if (taskExecutor == null) {
            synchronized (TaskExecutor.class) {
                taskExecutor = new TaskExecutor();
            }
        }
        return taskExecutor;
    }

    public TaskExecutor() {
        this(corePoolSize, maximumPoolSize, keepAliveTime);
    }

    public TaskExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
        this.queue = new LinkedBlockingQueue<>();
        this.executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, queue);
        this.executor.allowCoreThreadTimeOut(true);
    }

    public void execute(Runnable task) {
        this.executor.execute(task);
    }

    /**
     * 获取队列数
     *
     * @return
     */
    public int getQueueSize() {
        return this.queue.size();
    }

    public < TResult> Future<TResult> submit(Callable<TResult> callable) {
        return this.executor.submit(callable);
    }
}
